package com.xky.ui.main;

import com.xky.ui.module.customersManagement.CustomersInfo;
import com.xky.ui.module.inventorManagement.InvenToryInfo;
import com.xky.ui.module.login.Login;
import com.xky.ui.module.productManagement.BasicMassageInfo;
import com.xky.ui.module.productManagement.ProductCategoryInfo;
import com.xky.ui.module.salesManagement.SalesInfo;
import com.xky.ui.module.salesManagement.SalesShipmentsInfo;
import com.xky.ui.module.supplierManagement.SupplierInfo;
import com.xky.ui.module.productManagement.select.ProductService;
import com.xky.ui.menu.MenuManager;
import lombok.Getter;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 主界面
 */
@Getter
public class MainView extends JFrame {
    private static JPanel leftPanel;
    public static JPanel rightPanel;
    private static JPanel contentPanel;
    private static JLabel statusMessageLabel;
    private static JLabel statusTimeLabel;
    private static Timer statusTimeTimer;

    public static Timer autoRefreshTimer;//定时器
    private static JLabel lastRefreshTimeLabel;
    private static String currentModuleName = "首页";
    private static Runnable currentRefreshAction = null;
    
    private ProductService productService;


    public MainView() {
        initializeFrame();
        initializeServices();
        initializeUI();
        setVisible(true);
    }

    private void initializeFrame() {
        setTitle("商品库存管理系统");
        setSize(1440, 900);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
    }

    private void initializeServices() {
        productService = new ProductService();
        // 初始化自动刷新定时器 (每10秒刷新一次)
        autoRefreshTimer = new Timer(10000, _ -> {
            if (currentRefreshAction != null) {
                currentRefreshAction.run();
                // 检查lastRefreshTimeLabel是否已初始化
                if (lastRefreshTimeLabel != null) {
                    updateRefreshTime();
                }
                updateStatusMessage(currentModuleName + "数据已自动刷新");
            }
        });
    }

    private void initializeUI() {
        // 创建主内容面板
        contentPanel = new JPanel(new BorderLayout());
        
        // 初始化左侧面板
        initializeLeftPanel();

        // 初始化右侧面板
        rightPanel = new JPanel(new BorderLayout());
        rightPanel.setBorder(new EmptyBorder(10, 10, 10, 10)); // 添加内边距
        rightPanel.setBackground(new Color(245, 245, 245)); // 浅灰色背景

            // 创建顶部面板
            JPanel topPanel = new JPanel(new BorderLayout());
            topPanel.setOpaque(false);
            
            // 创建用户信息面板（右对齐）
            JPanel userInfoPanel = new JPanel();
            userInfoPanel.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 0));
            userInfoPanel.setOpaque(false);
            userInfoPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
            
            // 创建用户信息背景面板
            JPanel userBgPanel = new JPanel(new BorderLayout(5, 0));
            userBgPanel.setBackground(new Color(48, 57, 82)); // 深蓝色背景，与左侧面板一致
            userBgPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 5));
            
            // 创建用户信息子面板
            JPanel userInfoSubPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
            userInfoSubPanel.setOpaque(false);
            
            // 用户图标
            JLabel userIconLabel = new JLabel();
            userIconLabel.setFont(new Font("黑体", Font.PLAIN, 16));
            userIconLabel.setForeground(Color.WHITE);

            
            // 添加用户信息到子面板
            userInfoSubPanel.add(userIconLabel);

            
            // 添加子面板和按钮面板到用户背景面板
            userBgPanel.add(userInfoSubPanel, BorderLayout.CENTER);
            
            // 添加用户背景面板到用户信息面板
            userInfoPanel.add(userBgPanel);
            
            // 添加用户信息面板到顶部面板
            topPanel.add(userInfoPanel, BorderLayout.EAST);
            
            // 添加顶部面板到右侧面板
            rightPanel.add(topPanel, BorderLayout.CENTER);

        
        contentPanel.add(rightPanel, BorderLayout.CENTER);
        
        // 添加内容面板到主窗口
        add(contentPanel, BorderLayout.CENTER);

        //添加顶部状态栏
        topStatus();

        // 添加底部状态栏
        bottomStatus();

        // 显示首页
        BasicMassageInfo.showHomePage();
        updateStatusMessage("欢迎使用商品库存管理系统");
    }

    // 初始化左侧面板
    private void initializeLeftPanel() {
        leftPanel = new JPanel();
        leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
        leftPanel.setBackground(new Color(48, 57, 82)); // 深蓝色背景
        leftPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); // 移除内边距
        
        // 使用一个包装面板来确保左侧面板填满高度
        JPanel wrapperPanel = new JPanel(new BorderLayout());
        wrapperPanel.setBackground(new Color(48, 57, 82));
        wrapperPanel.add(leftPanel, BorderLayout.NORTH);
        
        // 设置固定宽度但允许高度自适应
        wrapperPanel.setPreferredSize(new Dimension(180, Integer.MAX_VALUE));

        // 添加系统标题
        JLabel titleLabel = new JLabel("库存管理系统");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 22)); // 增大字体
        titleLabel.setForeground(Color.WHITE);
        titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT); // 居中对齐
        titleLabel.setBorder(BorderFactory.createEmptyBorder(20, 0, 25, 0)); // 增加上下间距
        leftPanel.add(titleLabel);

        // 设置鼠标悬停效果
        titleLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        titleLabel.setForeground(new Color(150, 200, 255));

     // 添加鼠标事件监听器
        titleLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                // 点击标题时执行的操作
                dispose();
              new MainView();
              updateRefreshTime();
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                // 鼠标悬停时改变颜色
                titleLabel.setForeground(Color.YELLOW);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                // 鼠标离开时恢复颜色
                titleLabel.setForeground(new Color(150, 200, 255));
            }
        });
        // 创建菜单管理器
        new MenuManager(leftPanel);

        // 首页按钮
        JButton homeButton = createMenuButton("首页", new ImageIcon(""));
        homeButton.addActionListener(e -> BasicMassageInfo.showHomePage());
        leftPanel.add(homeButton);

        // 分割线
        JSeparator separator = new JSeparator();
        separator.setMaximumSize(new Dimension(180, 1));
        separator.setForeground(new Color(70, 80, 110));
        leftPanel.add(separator);

        // 添加菜单
        addMenuItems();

        // 添加一个弹性组件，使菜单项靠顶部显示
        leftPanel.add(Box.createVerticalGlue());
        
        contentPanel.add(wrapperPanel, BorderLayout.WEST);
    }

    /**
     * 初始化底部状态栏
     */
    private void bottomStatus() {
        JPanel statusBar = new JPanel(new BorderLayout());
        statusBar.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(200, 200, 200)),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)
        ));
        statusBar.setBackground(new Color(240, 240, 240));

        // 左侧面板 - 包含状态消息
        JPanel leftStatusPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0));
        leftStatusPanel.setOpaque(false);

        // 状态消息标签
        statusMessageLabel = new JLabel("就绪");
        statusMessageLabel.setForeground(new Color(100, 100, 100));
        leftStatusPanel.add(statusMessageLabel);

        // 最后刷新时间标签
        lastRefreshTimeLabel = new JLabel("尚未刷新");
        lastRefreshTimeLabel.setForeground(new Color(100, 100, 100));
        leftStatusPanel.add(lastRefreshTimeLabel);

        statusBar.add(leftStatusPanel, BorderLayout.WEST);

        // 时间标签
        statusTimeLabel = new JLabel();
        statusTimeLabel.setForeground(new Color(100, 100, 100));
        statusBar.add(statusTimeLabel, BorderLayout.EAST);

        // 添加时间更新定时器
        statusTimeTimer = new Timer(1000, e -> updateStatusBarTime());
        statusTimeTimer.start();
        updateStatusBarTime(); // 立即更新一次

        add(statusBar, BorderLayout.SOUTH);
    }
    /**
     * 初始化顶部状态栏
     */
    private void topStatus() {
        JPanel topStatus = new JPanel(new BorderLayout());
        topStatus.setPreferredSize(new Dimension(getWidth(), 35));
        topStatus.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(200, 200, 200)),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)
        ));
        topStatus.setBackground(new Color(240, 240, 240));
        
        // 左侧系统状态信息
        JPanel leftPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        leftPanel.setOpaque(false);
        JLabel statusLabel = new JLabel("系统状态：已登录  |  登录角色：admin  |");
        statusLabel.setFont(new Font("黑体", Font.PLAIN, 14));
        statusLabel.setForeground(new Color(70, 70, 70));
        leftPanel.add(statusLabel);
        topStatus.add(leftPanel, BorderLayout.WEST);
        
        // 右侧退出按钮
        JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        rightPanel.setOpaque(false);
        JButton logoutButton = new JButton("退出系统");
        logoutButton.setFont(new Font("黑体", Font.PLAIN, 14));
        logoutButton.setForeground(new Color(70, 70, 70));
        logoutButton.setOpaque(false);
        logoutButton.setBorderPainted(false);
        logoutButton.setContentAreaFilled(false);
        logoutButton.setFocusPainted(false);
        logoutButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        // 添加鼠标悬停效果
        logoutButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                logoutButton.setForeground(new Color(220, 0, 0));
            }
            
            public void mouseExited(java.awt.event.MouseEvent evt) {
                logoutButton.setForeground(new Color(70, 70, 70));
            }
        });
        
        rightPanel.add(logoutButton);
        topStatus.add(rightPanel, BorderLayout.EAST);
        
        add(topStatus, BorderLayout.NORTH);

        // 点击事件
        logoutButton.addActionListener(_ -> {
            int i = JOptionPane.showConfirmDialog(MainView.this, "你确定要退出系统吗？", "退出提示", JOptionPane.OK_CANCEL_OPTION);
            if (i == 0) {
                dispose();
                new Login();
            }
        });
    }
    
    /**
     * 更新状态栏时间
     */
    private void updateStatusBarTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        statusTimeLabel.setText(sdf.format(new Date()));
    }
    
    /**
     * 更新状态栏消息
     */
    public static void updateStatusMessage(String message) {
        if (statusMessageLabel != null) {
            statusMessageLabel.setText(message);
        }
    }

    /**
     * 更新最后刷新时间
     */
    private static void updateRefreshTime() {
        if (lastRefreshTimeLabel != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            lastRefreshTimeLabel.setText("最后刷新: " + sdf.format(new Date()));
        }
    }
    
    /**
     * 注册模块的刷新操作
     * @param moduleName 模块名称
     * @param refreshAction 刷新操作
     */
    public static void registerRefreshAction(String moduleName, Runnable refreshAction) {
        currentModuleName = moduleName;
        currentRefreshAction = refreshAction;
        
        // 更新刷新时间
        if (lastRefreshTimeLabel != null) {
            updateRefreshTime();
        }
        
        // 自动刷新始终启用
        if (autoRefreshTimer != null) {
            autoRefreshTimer.restart();
        }
    }
    
    /**
     * 取消注册刷新操作
     */
    public static void unregisterRefreshAction() {
        currentModuleName = "首页";
        currentRefreshAction = null;
        
        // 停止自动刷新
        if (autoRefreshTimer != null && autoRefreshTimer.isRunning()) {
            autoRefreshTimer.stop();
        }
        
        // 更新状态
        if (lastRefreshTimeLabel != null) {
            lastRefreshTimeLabel.setText("尚未刷新");
        }
    }


    /**
     * 创建统一风格的菜单按钮
     * @param text 按钮文本
     * @return 创建的按钮
     */
    public static JButton createMenuButton(String text, ImageIcon icon) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 16));
        button.setForeground(Color.WHITE);
        button.setMaximumSize(new Dimension(180, 45)); // 增加按钮高度
        button.setPreferredSize(new Dimension(180, 45));
        button.setAlignmentX(Component.CENTER_ALIGNMENT); // 居中对齐
        button.setHorizontalTextPosition(SwingConstants.RIGHT);
        button.setHorizontalAlignment(SwingConstants.LEFT);
        button.setOpaque(false);
        button.setContentAreaFilled(false);
        button.setBorderPainted(false);
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
        button.setBorder(BorderFactory.createEmptyBorder(8, 20, 8, 0)); // 增加左侧内边距
        
        if (icon != null && icon.getIconWidth() > 0) {
            button.setIcon(icon);
        }
        
        // 添加鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(60, 70, 100));
                button.setOpaque(true);
            }
            
            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setOpaque(false);
            }
        });
        
        return button;
    }

    private void addMenuItems() {
        // 添加商品管理模块
        MenuManager.addMenu("商品管理模块", new String[]{"商品基础信息", "商品分类"},
            menuItem -> {
                if ("商品基础信息".equals(menuItem)) {
                   BasicMassageInfo.showProductInfoPage();
                   updateStatusMessage("已加载商品基础信息");
                } else if ("商品分类".equals(menuItem)) {
                    ProductCategoryInfo.showCategoryInfoPage();
                    updateStatusMessage("已加载商品分类信息");
                }
            }
        );

        // 添加库存管理模块
        MenuManager.addMenu("库存管理模块", new String[]{"库存信息"},
            menuItem -> {
                if ("库存信息".equals(menuItem)) {
                    InvenToryInfo.showInventoryInfoPage();
                    updateStatusMessage("已加载库存信息");
                }
            }
        );

        // 恢复供应商管理模块
        MenuManager.addMenu("供应商管理模块", new String[]{"供应商信息"},
            menuItem -> {
                if ("供应商信息".equals(menuItem)) {
                    SupplierInfo.showSupplierInfoPage();
                    updateStatusMessage("已加载供应商信息");
                }
            }
        );

        // 添加客户管理模块
        MenuManager.addMenu("客户管理模块", new String[]{"客户信息"},
            menuItem -> {
                if ("客户信息".equals(menuItem)) {
                    CustomersInfo.showCustomersPage();
                    updateStatusMessage("已加载客户信息");
                }
            }
        );

        // 添加销售模块
        MenuManager.addMenu("销售模块", new String[]{"销售订单信息", "销售发货信息"},
                menuItem -> {
                    if ("销售订单信息".equals(menuItem)){
                        SalesInfo.showSalesInfoPage();
                        updateStatusMessage("已加载销售订单信息");
                    }else if ("销售发货信息".equals(menuItem)){
                        SalesShipmentsInfo.showSalesShipmentsPage();
                        updateStatusMessage("已加载销售发货信息");
                    }

                }
        );

        // 添加仓库模块
        MenuManager.addMenu("仓库模块", new String[]{"仓库信息"},
            menuItem -> {
                if ("仓库信息".equals(menuItem)) {
                    com.xky.ui.module.warehouseManagement.WarehouseInfo.showWarehouseInfoPage();
                    updateStatusMessage("已加载仓库信息");
                }
            }
        );
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(MainView::new);
    }
}
